package cc.linker.steplink.crm.task;

import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchanth5.dao.EnrollActiveDao;
import cc.linker.steplink.crm.merchanth5.service.EnrollActiveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 报名活动后台任务
 */
@Slf4j
@Component
public class EnrollActiveTask {

    private static final String ENROLL_KEY = "enroll:enrollactive_limit_option_";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private EnrollActiveDao enrollActiveDao;
    @Autowired
    private EnrollActiveService enrollActiveService;


    /**
     * 取消一小时未付款订单
     */
    @RedisLock("cancelEnrollRecord")
    @Scheduled(cron = "0 */10 * * * ?")
    public void cancelEnrollRecord(){
        List<Map<String, Object>> unpayList = enrollActiveDao.getUnpayList();
        if(null == unpayList || unpayList.size()==0){
            return;
        }
        for(Map<String, Object> record:unpayList){
            Map<String, Object> info = enrollActiveDao.getInfo(record);
            Date ttlTime = null;
            if (!StringUtils.isEmpty(info.get("endTime"))) {
                String endTime = info.get("endTime").toString();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    ttlTime = simpleDateFormat.parse(endTime);
                } catch (ParseException e) {
                    ttlTime = null;
                }
            }
            String optionId = (String) record.get("optionId");
            //60分钟还没支付，名额回滚，报名人数减去，redis list加回名额，删除订单
            String key = ENROLL_KEY + optionId;
            stringRedisTemplate.opsForList().leftPush(key, "1");
            if(null != ttlTime){
                stringRedisTemplate.expireAt(key,ttlTime);
            }
            enrollActiveDao.cutExistNum(record);
            enrollActiveDao.delRecrodByEnrollIdAndCustomerId(record);
        }
    }


    /**
     * 报名支付回调重试
     * @throws IOException
     * @throws URISyntaxException
     */
    @RedisLock("enrollNotifyRetry")
    @Scheduled(initialDelay=1000, fixedDelay=20000)
    public void enrollNotifyRetry() throws IOException, URISyntaxException {
        Long enrollNotifyRetryListSize = stringRedisTemplate.opsForList().size("enrollNotifyRetryList");
        if (null != enrollNotifyRetryListSize && enrollNotifyRetryListSize > 0) {
            for (int i = 0; i < enrollNotifyRetryListSize; i++) {
                String enrollNotifyRetry = stringRedisTemplate.opsForList().rightPop("enrollNotifyRetryList");
                if (!StringUtils.isEmpty(enrollNotifyRetry)) {
                    Map<String, Object> data = (Map) JSON.parse(enrollNotifyRetry);
                    //重试次数
                    String rKey = "enrollnotifyretrytime:key_" + data.get("orderSn");
                    String retryTime = stringRedisTemplate.opsForValue().get(rKey);
                    if(StringUtils.isEmpty(retryTime) || Integer.valueOf(retryTime)<5){
                        enrollActiveService.enrollCallback(data);
                        stringRedisTemplate.opsForValue().increment(rKey);
                        stringRedisTemplate.expire(rKey,1, TimeUnit.DAYS);
                    }else{
                        LOGGER.error("enrollCallBack:回调重试次数已达到5次，param："+enrollNotifyRetry);
                    }
                }
            }
        }
    }


}
